package com.bizmda.bizsip.sink.connector;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.config.AbstractSinkConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shizhengye
 */
@Slf4j
public class HttpPostSinkConnector extends AbstractSinkConnector implements ByteProcessInterface {
    private String url;
    private Map<String,String> headers;
    private String charset;

    @Override
    public void init(AbstractSinkConfig sinkConfig) throws BizException {
        super.init(sinkConfig);
        this.url = (String) sinkConfig.getConnectorMap().get("url");
        this.headers = (Map<String, String>) sinkConfig.getConnectorMap().get("headers");
        if (this.headers == null) {
            this.headers = new HashMap<>();
        }
        this.charset = CharSequenceUtil.blankToDefault((String) sinkConfig.getConnectorMap().get("charset"), "utf-8");
        log.info("初始化HttpSinkConnector:url[{}],content-type[{}],charset[{}]", this.url, this.headers, this.charset);
    }

    @Override
    public byte[] process(byte[] inMessage) throws BizException {
        HttpResponse httpResponse;
        HttpRequest httpRequest = HttpUtil.createPost(this.url);
        for(Map.Entry<String,String> entry:this.headers.entrySet()) {
            httpRequest = httpRequest.header(entry.getKey(),entry.getValue());
        }
        httpResponse = httpRequest.body(inMessage).charset(this.charset)
                .execute().charset(this.charset);
        return httpResponse.bodyBytes();
    }
}
